<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Backend_administrator Extends MY_Controller
{
	private $__username = 'backend001';
	private $__password = 'p1backend001';
	
	public function __construct()
	{
		parent::__construct();
		$this->layout_view = 'application_no_side_bar_no_header';
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
	}

	public function index()
	{
		$this->_secure();
		
		// For Site Settings
		$this->view_data['data'] = $this->_get_data();
		
		if($this->input->post('save_backend_settings'))
		{
			$post = $this->input->post();
			if($this->_update_insert_data($post))
			{
				$this->_msg('s','Save was successfull','backend_administrator#site-settings');
			}else{
				$this->_msg('e','Save Failed','backend_administrator#site-settings');
			}
		}
		
		//For add users
		
		$this->view_data['usertypes'] = array('president'=>'President',
									  'admin'=>'Site Administrator',
									  'evaluation'=>'School Evaluation',
									  'finance'=>'School Finance',
									  'cashier'=>'School Cashier',
									  'registrar'=>'School Registrar',
									  'hrd'=>'School HRD',
									  'teacher'=>'School teacher',
									  'librarian'=>'School Librarian',
									  'custodian'=>'School Custodian'
									 );
		if($this->input->post('save_temporary_users'))
		{
			$this->load->model('M_users','mu');
			if($this->mu->save_temporary_users($this->input->post('user'),$this->input->post('profile')))
			{
				$this->_msg('s','User Added','backend_administrator#add-users');
			}else{
				$this->_msg('e','Unable to add user','backend_administrator#add-users');
			}
		}
	}
	
	public function login()
	{
		if($this->uri->segment(1) == 'bea' AND $this->uri->segment(1) !== NULL)
		{
			if($this->session->userdata('bsadministrator') == FALSE)
			{
				$this->view_data['system_message']= $this->_msg();
				$this->load->library('token');
				$captcha = $this->captcha();
				$this->view_data['form_token'] = $this->token->get_token();
				$this->load->library('form_validation');
				$this->form_validation->set_rules('username', 'username', 'required|trim|htmlspecialchars');
				$this->form_validation->set_rules('password', 'password', 'required|trim|htmlspecialchars');
				$this->form_validation->set_rules('captcha_text', 'captcha', 'required|trim|htmlspecialchars');

				$this->view_data['captcha_image'] = $captcha->image;
				
				if($this->input->post('backstage_login'))
				{
					if($this->token->validate_token($this->input->post('form_input_token',TRUE)))
					{
						if($this->form_validation->run() !== FALSE)
						{
							$captcha_word = md5($this->session->userdata('word'));
							$sent_captcha_text = md5($this->input->post('captcha_text'));
							if($captcha_word == $sent_captcha_text)
							{
								$post_vars = (object)$this->input->post();
								if($this->_validate($post_vars) == TRUE)
								{
									$this->token->destroy_token();
									$this->session->set_userdata('word','');
									unlink($captcha->link);
									$this->_msg('s','Login Successfull, Welcome','bea');
								}else
								{
									$this->token->destroy_token();
									$this->session->set_userdata('word','');
									unlink($captcha->link);
									$this->_msg('e','Invalid username/password Combination','bea');
								}
							}else{
								$this->token->destroy_token();
								$this->session->set_userdata('word','');
								unlink($captcha->link);
								$this->_msg('e','wrong Captcha Code Entered','bea');
							}
						}
					}else{
						$this->token->destroy_token();
						$this->session->set_userdata('word','');
						unlink($captcha->link);
						$this->_msg('e','Invalid username/password Combination','backend_administrator/login/');
					}
				}else{
					$this->session->set_userdata('word',$captcha->word);
				}
			}else{
				redirect('backend_administrator/settings');
			}
		}else{
			show_error('Unable to Find Page',404);
		}
	}
	
	private function _secure($login = FALSE)
	{
		return TRUE;
	}

	public function captcha()
	{
		$this->load->helper('captcha');
		$vals = array(
			'word'	 => substr(md5(rand(1,100)),3,3),
			'img_path'	 => './captcha/',
			'img_url'	 => base_url().'backend_administrator/captcha',
			'font_path'	 => './assets/_fonts/4.ttf',
			'img_width'	 => '150',
			'img_height' => 35,
			'expiration' => 7200
			);
		
		$cap = create_captcha($vals);
		$image['word'] = $cap['word'];
		$image['image'] ='<image src="'.base_url().'captcha/'.$cap['time'].'.jpg"/>';
		$image['link'] = './captcha/'.$cap['time'].'.jpg';

		return (object)$image;
	}
	
	private function _validate($p = FALSE)
	{
		if($p !== FALSE)
		{
			$password = md5(str_pad($this->__password, 10, "_", STR_PAD_BOTH));
			$username = md5(str_pad($this->__username, 10, "_", STR_PAD_BOTH));
			
			$i_username = md5(str_pad($p->username, 10, "_", STR_PAD_BOTH));
			$i_password = md5(str_pad($p->password, 10, "_", STR_PAD_BOTH));
			
			if($password == $i_password AND $i_username == $username)
			{
				$this->session->set_userdata('bsadministrator',TRUE);
				return TRUE;
			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}
	}
	
	
	/*
		QUERIES
	*/
	private function _get_data()
	{
		$sql = 'SELECT * FROM backend_settings';
		$query = $this->db->query($sql);
		return $query->num_rows() >=1 ? $query->row() : FALSE;
	}
	
	private function _update_insert_data($data = FALSE)
	{
		if($data !== FALSE)
		{
			$data = (object)$data;
			$check = $this->_get_data();
			
			$input['enrollment_link'] = html_entity_decode($data->enrollment_link);
			$input['student_link'] = html_entity_decode($data->student_link);
			$input['system_link'] = html_entity_decode($data->system_link);
			$input['accounting_link'] = html_entity_decode($data->accounting_link);
			
			if($check == FALSE)
			{
				//insert
				$this->db->insert('backend_settings',$input);
				return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
			
			}else{
				//update
				$this->db->set($input)->where('id',$check->id)->update('backend_settings');
				return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
			}
		}
		return FALSE;
	}
	
	
	public function logout()
	{
		$this->session->sess_destroy();
		redirect('');
	}
}